<template>
	<div class="app-container base-alarm-list-class">
		<yd-form ref="myForm" class="yd-form-wraper" :options="formOptions" :model="formData" @form-init="formInited" @search="formInited">
			<template #form-btn>
				<el-button type="primary" icon="Search" @click="searchHandler">查 询</el-button>
				<el-button style="margin-left: 15px" type="primary" :disabled="downLoadDisbled" @click="downloadHandler">下载</el-button>
				<el-button style="margin-left: 15px" type="primary" @click="showInitDialog">自定义列</el-button>
			</template>
		</yd-form>

		<div v-if="dataForm.relvanceDataId != null" vclass="relvanceDataIdClass">附加条件的数据id：{{ dataForm.relvanceDataId }}</div>

		<div v-if="route.query.responseIp" class="relvanceDataIdClass">
			附加条件：响应IP端口：{{ route.query.responseIp + ':' + route.query.responsePort }}
		</div>

		<el-tabs v-model="dataForm.headActiveTabs" size="small">
			<el-tab-pane label="首端" name="headerFlag_1" :class="selectTabHandle(dataForm.headActiveTabs)">
				<!-- 列表 -->
				<YdCard>
					<YdTable
						:formData="headerFormData"
						:tableConfig="tableConfig"
						:tableData="tableData.data"
						@sizeChangeHandler="queryGridByCloneData1"
						@currentChangeHandler="queryGridByCloneData"
						@sortChangeHandler="queryGridByCloneData"
					></YdTable>
				</YdCard>
			</el-tab-pane>
			<el-tab-pane label="非首端" name="headerFlag_0" :class="selectTabHandle(dataForm.headActiveTabs)">
				<!-- 列表 -->
				<YdCard>
					<YdTable
						:formData="noHeadFormData"
						:tableConfig="noHeadTableConfig"
						:tableData="noHeadTableData.data"
						@sizeChangeHandler="noHeadQueryGridByCloneData1"
						@currentChangeHandler="noHeadQueryGridByCloneData"
						@sortChangeHandler="noHeadQueryGridByCloneData"
					></YdTable>
				</YdCard>
			</el-tab-pane>
		</el-tabs>

		<!-- 首端自定义列弹出层 -->
		<custom-column ref="headCustomColumnRef" title="首端-自定义列" pageType="bpmAlarm"></custom-column>
		<!-- 非首端自定义列弹出层 -->
		<custom-column ref="noHeadCustomColumnRef" title="非首端-自定义列" pageType="bpmAlarm"></custom-column>
	</div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { getBaseAlarmList, exportBaseAlarmExcel } from '@/api/bpm/alarm/busi_detail_alarm';
import { parseTime } from '@/utils/common';
// import { queryDefaultAppSystemOptions } from '@/api/search/searchOptions';
import CustomColumn from '@/components/CustomColumn/index.vue';
import { onMounted, ref, reactive, getCurrentInstance, onActivated, nextTick, watch, computed } from 'vue';
import useUserStore from '@/store/modules/userinfo';
const instance = getCurrentInstance();
const proxy = instance?.proxy;

const route = useRoute();
const router = useRouter();

// refs
const headCustomColumnRef = ref<InstanceType<typeof CustomColumn>>();
const noHeadCustomColumnRef = ref<InstanceType<typeof CustomColumn>>();
const myForm = ref();

const dataForm = reactive({
	headActiveTabs: 'headerFlag_1',
	relvanceDataId: null,
});

let formData = reactive<FormModelType>({
	category: 'BPM',
});

// 表单配置
const formOptions = ref<FormOptionType>([
	{
		type: 'select',
		prop: 'systemId',
		label: '业务系统',
		api: {
			name: 'queryAppSystemOptions',
			params: { isStatus: 1 },
		},
		cascaders: [
			{
				api: {
					name: 'queryBusinessOptions',
				},
				cascadersParams: 'businessCodeList',
			},
			{
				api: {
					name: 'querySegmentOptions',
				},
				cascadersParams: 'segmentIds',
			},
		],
	},

	{
		type: 'select',
		prop: 'segmentIds',
		label: '告警网端',
		attrs: {
			multiple: true,
		},
	},
	{
		type: 'select',
		prop: 'businessCodeList',
		label: '告警业务',
		attrs: {
			multiple: true,
		},
	},
	{
		type: 'select',
		prop: 'stepCodes',
		label: '告警步骤',
		api: {
			name: 'queryStepOptions',
		},
		attrs: {
			multiple: true,
		},
		isInitValue: false,
		isInitOption: false,
		hide: true,
	},
	{
		type: 'select',
		prop: 'alarmStates',
		label: '告警分类',
		attrs: {
			multiple: true,
		},
		children: [
			{
				label: '失败',
				value: '0',
			},
			{
				label: '普通',
				value: '1',
			},
		],
	},
	{
		type: 'select',
		prop: 'alarmIndicatorIds',
		label: '告警类型',
		api: {
			name: 'queryBaseIndicatorsOptions',
			params: {
				category: 'BPM',
			},
		},
		attrs: {
			multiple: true,
		},
	},
	{
		type: 'select',
		prop: 'alarmLevelIds',
		label: '告警级别',
		api: {
			name: 'queryAlarmLevelOptions',
		},
		attrs: {
			multiple: true,
		},
	},
	{
		type: 'input',
		prop: 'alarmObject',
		label: '告警对象',
	},

	{
		type: 'date-picker',
		prop: 'dateRange',
		span: 8,
		dateType: 'datetimerange',
		label: '时间范围',
		enableCrossDay: true,
	},
	{
		type: 'input',
		prop: 'exclusiveIndicator',
		label: '专属指标',
	},
]);

// 首端搜索表单数据
const headerFormData = reactive<FormModelType>({
	headerFlag: 1,
});
const cloneHeaderFormData = ref<FormApiType>();
// 首端列表配置
const tableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '告警对象',
			prop: 'alarmObject',
			align: 'left',
			hide: true,
			width: 120,
		},
		{
			label: '所属步骤',
			prop: 'stepName',
			hide: false,
			width: 130,
		},
		{
			label: '所属业务',
			prop: 'businessName',
			hide: false,
			width: 130,
		},
		{
			label: '所属网端',
			prop: 'segmentName',
			hide: true,
			width: 120,
		},
		{
			label: '所属系统',
			prop: 'systemName',
			hide: true,
			width: 120,
		},
		{
			label: '告警级别',
			prop: 'alarmLevelName',
			hide: false,
			width: 90,
		},
		{
			label: '告警现象',
			prop: 'alarmContext',
			hide: false,
			width: 550,
		},
		{
			label: '告警类型',
			prop: 'alarmIndicatorName',
			hide: false,
			width: 120,
		},
		{
			label: '告警时间',
			prop: 'alarmTriggerTime',
			sortable: true,
			hide: false,
			width: 170,
		},
		{
			label: '请求IP端口',
			prop: 'requestIpPort',
			hide: true,
			width: 170,
			formatter: (row, val) => {
				return row.requestIp + ':' + row.requestPort;
			},
		},
		{
			label: '响应IP端口',
			prop: 'responseIpPort',
			hide: true,
			width: 170,
			formatter: (row, val) => {
				return row.responseIp + ':' + row.responsePort;
			},
		},
		{
			label: '请求大小',
			prop: 'requestBytes',
			formatter: (row, val) => {
				return formatByteData(val);
			},
			sortable: true,
			hide: false,
			width: 120,
		},
		{
			label: '响应大小',
			prop: 'responseBytes',
			formatter: (row, val) => {
				return formatByteData(val);
			},
			sortable: true,
			hide: false,
			width: 120,
		},
		{
			label: '专属指标',
			prop: 'exclusiveIndicator',
			isExclusive: true,
			hide: true,
			width: 150,
		},
		{
			label: '操作',
			prop: 'opera',
			width: 100,
			operation: [
				{
					text: '详情',
					handler: (scope) => getDetailHandle(scope.row),
				},
			],
		},
	],
	pagination: {
		pageNum: 1,
		pageSize: 10,
		orderByColumn: 'alarmTriggerTime',
		isAsc: 'desc',
	},
	loading: true,
});
// 首端列表数据
const tableData = reactive({
	data: [],
});
// 非首端搜索表单数据
const noHeadFormData = reactive({
	pageNum: 1,
	pageSize: 10,
	headerFlag: 0,
});
const cloneNoHeadFormData = ref<FormModelType>();
// 非首端列表配置
const noHeadTableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '告警对象',
			prop: 'alarmObject',
			align: 'left',
			hide: false,
			width: 150,
		},
		{
			label: '所属网端',
			prop: 'segmentName',
			hide: false,
			width: 120,
		},
		{
			label: '所属系统',
			prop: 'systemName',
			hide: true,
			width: 120,
		},
		{
			label: '告警级别',
			prop: 'alarmLevelName',
			hide: false,
			width: 90,
		},
		{
			label: '告警现象',
			prop: 'alarmContext',
			hide: false,
			width: 550,
		},
		{
			label: '告警类型',
			prop: 'alarmIndicatorName',
			hide: false,
			width: 120,
		},
		{
			label: '告警时间',
			prop: 'alarmTriggerTime',
			sortable: true,
			hide: false,
			width: 170,
		},
		{
			label: '请求IP端口',
			prop: 'requestIpPort',
			hide: true,
			width: 170,
			formatter: (row, val) => {
				return row.requestIp + ':' + row.requestPort;
			},
		},
		{
			label: '响应IP端口',
			prop: 'responseIpPort',
			hide: true,
			width: 170,
			formatter: (row, val) => {
				return row.responseIp + ':' + row.responsePort;
			},
		},

		{
			label: '请求大小',
			prop: 'requestBytes',
			formatter: (row, val) => {
				return formatByteData(val);
			},
			sortable: true,
			hide: false,
			width: 120,
		},
		{
			label: '响应大小',
			prop: 'responseBytes',
			formatter: (row, val) => {
				return formatByteData(val);
			},
			sortable: true,
			hide: false,
			width: 120,
		},
		{
			label: '专属指标',
			prop: 'exclusiveIndicator',
			isExclusive: true,
			hide: true,
			width: 150,
		},
		{
			label: '操作',
			prop: 'opera',
			width: 100,
			operation: [
				{
					text: '详情',
					handler: (scope) => getDetailHandle(scope.row),
				},
			],
		},
	],
	pagination: {
		pageNum: 1,
	},
	loading: true,
});
// 非首端列表数据
const noHeadTableData = reactive({
	data: [],
	total: 0,
});
const fromRule = reactive({
	queryColumnValue: [{ required: true, message: '', trigger: 'blur' }],
});
const downloadStartTime = ref('');
const downloadEndTime = ref('');
const options = ref<anyObj[]>([]);
const downloading = ref(false);
let pageInit = ref(true);

const downLoadDisbled = computed(() => {
	if (dataForm.headActiveTabs === 'headerFlag_0') {
		return noHeadTableData.data.length === 0;
	} else {
		return tableData.data.length === 0;
	}
});

watch(
	() => formData.businessCodeList,
	(newval, oldval) => {
		if (newval.length !== 0) {
			if (newval[0]) {
				// 业务有值才去请求
				let params = {
					systemId: formData.systemId,
					businessCodes: newval,
				};
				myForm.value?.setOptions('stepCodes', params);
			}
		} else {
			// 清空业务步骤
			myForm.value?.clearValue('stepCodes');
		}
	},
	{ deep: true }
);

initQuery(route.query, formData);
onMounted(() => {
	dataForm.relvanceDataId = formData.relvanceDataId;

	nextTick(() => {
		headCustomColumnRef.value?.useCustomColumn('bpm3.customField.businessAlarmList.head', tableConfig.columns);

		noHeadCustomColumnRef.value?.useCustomColumn('bpm3.customField.businessAlarmList.noHead', noHeadTableConfig.columns);
	});
});

// 格式化传过来的参数
function initQuery(query: anyObj, formData: FormModelType) {
	try {
		let data = JSON.parse(query.data);
		if (data.category === 'NPM') {
			return false;
		}
		for (let key in data) {
			formData[key] = data[key];
		}
	} catch (err) {
		if (query.category === 'NPM') {
			return false;
		}
		for (let key in query) {
			formData[key] = query[key];
		}
	}

	if (formData.systemId) {
		formData.systemId = String(formData.systemId);
	}
	if (formData.alarmIndicatorIds) {
		formData.alarmIndicatorIds = formData.alarmIndicatorIds.map((item: any) => String(item));
	}
	if (formData.alarmLevelIds) {
		formData.alarmLevelIds = formData.alarmLevelIds.map((item: any) => String(item));
	}
	if (formData.alarmStates) {
		formData.alarmStates = formData.alarmStates.map((item: any) => String(item));
	}
	console.log('initquery---', formData);
}

function formatByteData(data: any) {
	if (Number(data) > 1024 * 1024) {
		return (data / 1024 / 1024).toFixed(2) + 'MB';
	}
	if (Number(data) > 1024) {
		return (data / 1024).toFixed(2) + 'KB';
	}
	return data + 'B';
}
// 表单初始化完毕
function formInited() {
	initQuery(route.query, formData);
	console.log('forminit----------1--', formData);

	tableConfig.pagination!.pageNum = 1;
	searchHandler(2);
}

// 搜索
function searchHandler(flag: any) {
	// tableConfig.loading = true;
	//当用户点击搜索的时候清空数据id
	if (flag !== 2) {
		dataForm.relvanceDataId = null;
		formData.relvanceDataId = null;
	}

	let start = formData.startTime;
	let end = formData.endTime;
	//点击自定义的时候将清理startTime和endTime
	if (start === null || end === null) {
		proxy?.$message.warning('开始和结束时间不能为空');
		tableConfig.loading = false;
		return;
	} else {
		//最近一小时跨天问题，以结束时间，如果最近一小时存在跨天，比如当前时间为2020-11-05 00:08:00，
		// 那么startTime="2020-11-05 00:00:00"  endTime="2020-11-05 00:08:00"。
		let startFormat = parseTime(start, '{y}-{m}-{d}');
		let startHmsFormat = parseTime(start, '{h}:{i}:{s}');
		let endFormat = parseTime(end, '{y}-{m}-{d}');
		let endHmsFormat = parseTime(end, '{h}:{i}:{s}');
		let endTime = new Date(end);
		let sumTime = endTime.getHours() + endTime.getMinutes() + endTime.getSeconds();
		let old_time = new Date(endFormat.replace(/-/g, '/'));
		let new_time = new Date(old_time.getTime() - 24 * 3600 * 1000);
		let new_format = parseTime(new_time, '{y}-{m}-{d}');
	}
	formData.startTime = start;
	formData.endTime = end;
	noHeadFormData.pageNum = 1;
	headerFormData.pageNum = 1;
	queryGrid();
	noHeadQueryGrid();
}
// 去掉空字符串""
function sliceEmptyString(formData: any) {
	for (let key in formData) {
		if (formData[key] instanceof Array) {
			if (formData[key].length === 1 && formData[key][0] === '') {
				formData[key] = [];
			}
		} else {
			if (formData[key] === '') {
				delete formData[key];
			}
		}
	}
	return formData;
}

// 查询首端列表数据
function queryGrid(cloneDataFlag?: boolean) {
	// let data = null;
	// if (cloneDataFlag) {
	// 	data = {
	// 		...cloneHeaderFormData.value,
	// 		...headerFormData,
	// 	};
	// } else {
	// 	// 深复制
	// 	data = {
	// 		...JSON.parse(JSON.stringify(formData)),
	// 		...headerFormData,
	// 		headerFlag: 1,
	// 	};
	// 	cloneHeaderFormData.value = JSON.parse(JSON.stringify(data));
	// }
	let data = {
		...headerFormData,
		...formData,
	};
	// console.log('headerFormData', headerFormData);
	// console.log('headerFormData', formData);
	downloadStartTime.value = data.startTime;
	downloadEndTime.value = data.endTime;
	tableConfig.loading = true;
	// sliceEmptyString(data);
	getBaseAlarmList(data).then((res: ApiResponse) => {
		if (res.code !== 0) {
			proxy?.$message.warning(res.msg);
			return;
		}
		if (res.msg !== 'success') {
			proxy?.$message.warning(res.msg);
		}
		tableConfig.loading = false;
		tableData.data = res.data.data;
		tableConfig.pagination!.total = res.data.total;
	});
}
function queryGridByCloneData() {
	queryGrid(true);
}
function queryGridByCloneData1() {
	noHeadFormData.pageNum = 1;
	headerFormData.pageNum = 1;
	queryGrid(true);
}
// 查询非首端列表数据
function noHeadQueryGrid(cloneDataFlag?: boolean) {
	// let data = null;
	// if (cloneDataFlag) {
	// 	data = {
	// 		...cloneNoHeadFormData.value,
	// 		...noHeadFormData,
	// 	};
	// } else {
	// 	// 深复制
	// 	data = {
	// 		...JSON.parse(JSON.stringify(formData)),
	// 		...noHeadFormData,
	// 		headerFlag: 0,
	// 	};
	// 	cloneNoHeadFormData.value = JSON.parse(JSON.stringify(data));
	// }
	// console.log('noHeadFormData', formData);
	// console.log('noHeadFormData', noHeadFormData);
	let data = {
		...noHeadFormData,
		...formData,
	};
	noHeadTableConfig.loading = true;
	// sliceEmptyString(data);
	getBaseAlarmList(data).then((res: ApiResponse) => {
		if (res.code !== 0) {
			proxy?.$message.warning(res.msg);
			return;
		}
		noHeadTableConfig.loading = false;
		noHeadTableData.data = res.data.data;
		noHeadTableConfig.pagination!.total = res.data.total;
	});
}
function noHeadQueryGridByCloneData() {
	noHeadQueryGrid(true);
}
function noHeadQueryGridByCloneData1() {
	noHeadFormData.pageNum = 1;
	headerFormData.pageNum = 1;
	noHeadQueryGrid(true);
}
// 下载
function downloadHandler() {
	let headerFlag = 1;
	if (dataForm.headActiveTabs === 'headerFlag_0') {
		// 非首端
		// if(noHeadTableData.data.length === 0) {

		// }
		headerFlag = 0;
		let list = [];
		let new_list = [];
		for (let i of noHeadTableConfig.columns) {
			if (!i.hide) {
				list.push(i.label);
				new_list.push(i.prop);
			}
		}
		formData.displayFields = list;
		formData.displayMappingFields = new_list;
	} else {
		let list = [];
		let new_list = [];
		for (let i of tableConfig.columns) {
			if (!i.hide) {
				list.push(i.label);
				new_list.push(i.prop);
			}
		}
		formData.displayFields = list;
		formData.displayMappingFields = new_list;
	}

	formData.headerFlag = headerFlag;
	formData.startTime = downloadStartTime.value;
	formData.endTime = downloadEndTime.value;

	formData.orderByColumn = headerFormData.orderByColumn;
	formData.isAsc = headerFormData.isAsc;
	for (let i of options.value) {
		if (formData.systemId === i.id) {
			formData.systemName = i.label;
		}
	}
	let data = {
		submitterId: useUserStore().userInfo?.userId,
		submitterName: useUserStore().userInfo?.username,
		submitTime: parseTime(new Date()),
		serviceCode: 'business-monitor',
		moduleName: 'BPM_WEB_MAIN',
		exportBtnName: '基础告警BPM列表下载',
		docExportParameterJson: JSON.stringify(formData),
		exportFileName: '基础告警BPM列表.xlsx',
		docHandleType: '2',
	};

	exportBaseAlarmExcel(data).then((res) => {
		proxy?.$message.success('已加入下载队列，请查看＂↓＂');
	});
}
//跳转到告警详情
function getDetailHandle(row: any) {
	let headerFlag = 1;
	if (dataForm.headActiveTabs === 'headerFlag_0') {
		headerFlag = 0;
	}
	router.push({
		path: '/business-monitor/monitor-query/base-alarm-detail',
		query: {
			id: row.id,
			startTime: formData.startTime,
			endTime: formData.endTime,
			headerFlag: headerFlag,
		},
	});
}
//tab是否选择样式
function selectTabHandle(selectVal: any) {
	if (selectVal) {
		return 'selectTabClass';
	}
	return 'noSelectTabClass';
}
// 自定义列点击事件
function showInitDialog() {
	if (dataForm.headActiveTabs === 'headerFlag_1') {
		headCustomColumnRef.value?.handleOpen('bpm3.customField.businessAlarmList.head', tableConfig.columns);
		// "首端";
	} else if (dataForm.headActiveTabs === 'headerFlag_0') {
		noHeadCustomColumnRef.value?.handleOpen('bpm3.customField.businessAlarmList.noHead', noHeadTableConfig.columns);
		// "非首端";
	}
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.base-alarm-list-class {
	/*整个tab靠上*/
	:deep(.el-tabs__nav-scroll) {
		margin-top: 0px;
	}
	:deep(.el-tabs__nav) {
		margin-left: 12px;
	}
	/*整个tab选中样式*/
	:deep(.el-tabs__active-bar) {
		height: 0px;
	}
	:deep(.el-tabs--top .el-tabs__item.is-top:nth-child(2)) {
		padding-left: 20px;
	}
	:deep(.el-tabs--top .el-tabs__item.is-top:last-child) {
		padding-right: 20px;
	}
	/*tab文字样式设置白色*/
	:deep(.el-tabs__item) {
		color: #ffffff;
		font-size: 16px;
		font-weight: bold;
		height: 32px;
		line-height: 32px;
	}
	/*tab文字在选中时颜色*/
	:deep(.el-tabs__item.is-active) {
		color: #ffffff;
		border: 1px solid #2abcca;
		border-radius: 6px;
		background: #2abcca;
		background: -moz-linear-gradient(top, rgba(43, 237, 237, 0.1) 0%, rgba(43, 237, 237, 0.5) 100%);
		background: -webkit-linear-gradient(top, rgba(43, 237, 237, 0.1) 0%, rgba(43, 237, 237, 0.5) 100%);
		background: linear-gradient(top, rgba(43, 237, 237, 0.1) 0%, rgba(43, 237, 237, 0.5) 100%);
	}
	/*tab下面的线的颜色*/
	:deep(.el-tabs__nav-wrap::after) {
		background-color: transparent;
	}

	.relvanceDataIdClass {
		margin-bottom: 10px;
		color: #2beded;
	}
}

:deep(.el-icon-edit-outline) {
	background: url('@/assets/icons/png/edit.png') no-repeat;
	background-size: 18px;
	&:before {
		content: '';
		font-size: 16px;
		visibility: hidden;
	}
}
.el-form-item__label {
	line-height: 36px;
}
:deep(.el-dialog__header .el-dialog__title) {
	background-image: url('@/assets/images/bpm/dialog/init-title.png');
	background-repeat: no-repeat;
	background-position: center;
	background-size: 100% 100%;
	color: #ffffff;
	font-size: 16px;
	display: inline-block;
	width: 215px;
	padding-left: 5px;
}

:deep(.el-checkbox__input.is-checked) {
	background-color: #2beded;
}
.style-split-yd-card {
	:deep(.el-card) {
		background-color: rgba(29, 39, 75, 0.31);
		border: unset;
		border-radius: 12px;
	}
}
</style>
